<template>
  <n-modal 
    v-model:show="showModal" 
    preset="card" 
    :style="{ width: '400px', maxWidth: '90vw' }"
    title="教练信息"
    size="small"
    @after-leave="onModalClose"
  >
    <template #header>
      <n-flex align="center" :size="12">
        <n-avatar
          round
          size="medium"
          :src="coachInfo?.avatarImgUrl ? BASE_URL + coachInfo.avatarImgUrl : '/default_avatar.svg'"
        />
        <n-space vertical size="small">
          <n-text strong>{{ coachInfo?.nickname || '教练' }}</n-text>
          <n-text depth="3" size="small">专业健身教练</n-text>
        </n-space>
      </n-flex>
    </template>

    <div v-if="loading" class="loading-container">
      <n-spin size="medium" />
      <n-text depth="3">正在加载教练信息...</n-text>
    </div>

    <div v-else-if="error" class="error-container">
      <n-text type="error">{{ error }}</n-text>
    </div>

    <div v-else class="coach-info-content">
      <!-- 资质证书 -->
      <div v-if="coachDetailInfo?.certification" class="info-section">
        <n-text strong class="section-title">资质证书</n-text>
        <div class="certification-container" @click="viewCertification">
          <n-image
            :src="coachDetailInfo.certification.startsWith('http') 
              ? coachDetailInfo.certification 
              : BASE_URL + coachDetailInfo.certification"
            class="certification-image"
            object-fit="cover"
            fallback-src="/default_certification.svg"
            preview-disabled
          />
          <n-button 
            text 
            type="primary" 
            size="small" 
            class="view-cert-btn"
            @click.stop="viewCertification"
          >
            <template #icon>
              <n-icon><Eye /></n-icon>
            </template>
            点击查看大图
          </n-button>
        </div>
      </div>

      <!-- 专业领域 -->
      <div v-if="coachDetailInfo?.specialty" class="info-section">
        <n-text strong class="section-title">专业领域</n-text>
        <n-flex :size="8">
          <n-tag 
            v-for="specialty in specialtyList" 
            :key="specialty" 
            type="info" 
            size="small"
            :bordered="false"
          >
            {{ specialty }}
          </n-tag>
        </n-flex>
      </div>

      <!-- 课时费用 -->
      <div v-if="coachDetailInfo?.hourlyRate" class="info-section">
        <n-text strong class="section-title">课时费用</n-text>
        <n-flex align="center" :size="8">
          <n-text type="primary" strong style="font-size: 18px;">
            ¥{{ coachDetailInfo.hourlyRate }}
          </n-text>
          <n-text depth="3" size="small">/课时</n-text>
        </n-flex>
      </div>

      <!-- 教学经验 -->
      <div v-if="coachDetailInfo?.teachingYears" class="info-section">
        <n-text strong class="section-title">教学经验</n-text>
        <n-flex align="center" :size="8">
          <n-text type="success" strong style="font-size: 16px;">
            {{ coachDetailInfo.teachingYears }}年
          </n-text>
          <n-text depth="3" size="small">专业教学经验</n-text>
        </n-flex>
      </div>

      <!-- 详细介绍 -->
      <div v-if="coachDetailInfo?.coachDesc" class="info-section">
        <n-text strong class="section-title">详细介绍</n-text>
        <div class="description-container">
          <n-text 
            :class="{ 'description-text': true, 'expanded': isDescExpanded }"
            v-html="formattedDescription"
          />
          <n-button 
            v-if="isDescriptionLong" 
            text 
            type="primary" 
            size="small" 
            @click="toggleDescription"
            class="expand-btn"
          >
            {{ isDescExpanded ? '收起' : '展开' }}
          </n-button>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <n-button type="primary" block @click="contactCoach">
          <template #icon>
            <n-icon><ChatbubbleEllipses /></n-icon>
          </template>
          联系教练
        </n-button>
      </div>
    </div>

    <!-- 证书预览模态框 -->
    <n-modal 
      v-model:show="showCertPreview" 
      preset="card" 
      title="资质证书"
      style="width: 80vw; max-width: 800px;"
    >
      <n-image
        v-if="coachDetailInfo?.certification"
        :src="coachDetailInfo.certification.startsWith('http') 
          ? coachDetailInfo.certification 
          : BASE_URL + coachDetailInfo.certification"
        style="width: 100%; height: auto;"
        object-fit="contain"
        fallback-src="/default_certification.svg"
      />
    </n-modal>
  </n-modal>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useMessage } from 'naive-ui'
import { useRouter } from 'vue-router'
import { Eye, ChatbubbleEllipses } from '@vicons/ionicons5'
import http from '@/utils/http'

// 获取用户信息的工具函数
function getUser() {
  const userStr = localStorage.getItem('user');
  return userStr ? JSON.parse(userStr) : null;
}

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  userId: {
    type: [Number, String],
    default: null
  },
  coachInfo: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:show'])

const message = useMessage()
const router = useRouter()
const BASE_URL = window.BASE_URL

// 响应式数据
const showModal = computed({
  get: () => props.show,
  set: (value) => emit('update:show', value)
})

const loading = ref(false)
const error = ref('')
const coachDetailInfo = ref(null)
const isDescExpanded = ref(false)
const showCertPreview = ref(false)

// 计算属性
const specialtyList = computed(() => {
  if (!coachDetailInfo.value?.specialty) return []
  return coachDetailInfo.value.specialty.split(/[,，、]/).map(s => s.trim()).filter(s => s)
})

const isDescriptionLong = computed(() => {
  if (!coachDetailInfo.value?.coachDesc) return false
  return coachDetailInfo.value.coachDesc.length > 100 || 
         coachDetailInfo.value.coachDesc.split('\n').length > 3
})

const formattedDescription = computed(() => {
  if (!coachDetailInfo.value?.coachDesc) return ''
  
  let desc = coachDetailInfo.value.coachDesc
  
  // 转换换行符为 <br>
  desc = desc.replace(/\n/g, '<br>')
  
  if (!isDescExpanded.value && isDescriptionLong.value) {
    // 截取前100个字符或前3行
    const lines = desc.split('<br>')
    if (lines.length > 3) {
      desc = lines.slice(0, 3).join('<br>') + '...'
    } else if (desc.length > 100) {
      desc = desc.substring(0, 100) + '...'
    }
  }
  
  return desc
})

// 方法
const fetchCoachInfo = async (userId) => {
  console.log('fetchCoachInfo 被调用, userId:', userId);
  if (!userId) {
    console.log('userId 为空，返回');
    return;
  }
  
  loading.value = true
  error.value = ''
  
  try {
    console.log('发送请求获取教练信息, userId:', userId);
    const response = await http.get('/v1/coach/selectByUserId', {
      params: { userId }
    })
    
    console.log('获取教练信息响应:', response.data);
    
    if (response.data.code === 2000 && response.data.data) {
      coachDetailInfo.value = response.data.data
      console.log('教练详情信息设置成功:', coachDetailInfo.value);
    } else {
      error.value = '未找到教练信息'
      console.log('未找到教练信息，响应代码:', response.data.code);
    }
  } catch (err) {
    console.error('获取教练信息失败:', err)
    error.value = '获取教练信息失败'
  } finally {
    loading.value = false
  }
}

const viewCertification = () => {
  showCertPreview.value = true
}

const toggleDescription = () => {
  isDescExpanded.value = !isDescExpanded.value
}

const contactCoach = async () => {
  // 检查用户是否登录
  const user = getUser()
  if (!user?.tokenInfo?.isLogin) {
    message.warning('请先登录后再联系教练')
    router.push('/login')
    return
  }
  
  if (!props.userId) {
    message.error('教练信息异常，无法建立联系')
    return
  }
  
  try {
    // 准备教练用户信息
    const coachUserInfo = {
      userId: props.userId,
      username: props.coachInfo?.nickname || coachDetailInfo.value?.coachName || '教练',
      avatar: props.coachInfo?.avatarImgUrl || coachDetailInfo.value?.avatarImgUrl || '/default_avatar.svg'
    }
    
    console.log('准备启动与教练的私聊:', coachUserInfo)
    
    // 创建或获取与教练的聊天会话
    const response = await http.post('/v1/chat/create', {
      sellerId: props.userId,
      sellerName: coachUserInfo.username,
      equipmentId: null, // 教练咨询不需要特定器械ID
      equipmentTitle: '教练咨询'
    })
    
    if (response.data.code === 2000) {
      message.success('正在为您连接教练...')
      
      // 关闭教练信息弹窗
      emit('update:show', false)
      
      // 跳转到聊天页面，并传递教练信息
      setTimeout(() => {
        router.push({
          path: '/chat',
          query: {
            sellerId: props.userId,
            sellerName: coachUserInfo.username,
            sellerAvatar: coachUserInfo.avatar
          }
        })
      }, 500)
      
    } else {
      console.error('创建聊天会话失败:', response.data)
      message.error(response.data.msg || '建立联系失败，请稍后重试')
    }
    
  } catch (error) {
    console.error('联系教练失败:', error)
    message.error('联系教练失败，请稍后重试')
  }
}

const onModalClose = () => {
  // 重置状态
  isDescExpanded.value = false
  coachDetailInfo.value = null
  error.value = ''
}

// 监听器
watch(() => props.userId, (newUserId) => {
  console.log('CoachInfoPopup userId 变化:', newUserId, 'show状态:', props.show);
  if (newUserId && props.show) {
    fetchCoachInfo(newUserId)
  }
}, { immediate: true })

watch(() => props.show, (show) => {
  console.log('CoachInfoPopup show 状态变化:', show, 'userId:', props.userId);
  if (show && props.userId) {
    console.log('准备获取教练信息, userId:', props.userId);
    fetchCoachInfo(props.userId)
  }
})
</script>

<style scoped>
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  padding: 40px 0;
}

.error-container {
  text-align: center;
  padding: 40px 0;
}

.coach-info-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.info-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.section-title {
  font-size: 14px;
  margin-bottom: 4px;
}

.certification-container {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  border: 1px solid #e0e0e6;
  transition: all 0.3s ease;
}

.certification-container:hover {
  border-color: #18a058;
  box-shadow: 0 2px 8px rgba(24, 160, 88, 0.15);
}

.certification-image {
  width: 100%;
  height: 120px;
  display: block;
}

.view-cert-btn {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  padding: 4px 8px;
}

.description-container {
  position: relative;
}

.description-text {
  line-height: 1.6;
  word-break: break-word;
  white-space: pre-wrap;
}

.description-text:not(.expanded) {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.expand-btn {
  margin-top: 8px;
}

.action-buttons {
  margin-top: 8px;
  padding-top: 16px;
  border-top: 1px solid #e0e0e6;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .coach-info-content {
    gap: 16px;
  }
  
  .certification-image {
    height: 100px;
  }
}
</style>
